$(function () {
    var content_ = "";
    var $search = parseSearch(),
        data = {}, arg = ''
    config = {
        queryAccount: '/payType/query?type=2',// // 供货地账户
    };
    arg = data[$search.type];
    onClick($('.add-new-var'), function () {
        var $tr = $(this).closest('.row').closest('.row');
        var $clone = '<div class="row var-item"> \
            <div class="col-sm-4"> \
            <input type="text" name="spec" class="form-control"/> \
            </div> \
            <div class="col-sm-7"> \
            <input disabled \
        name="tags-item" \
        class="form-control "/> \
            </div> \
            <div class="col-sm-1"> \
            <a href="javascript:void(0)" class="trash-btn "> \
            <i class="fa fa-trash "></i> \
            </a> \
            </div> \
            </div>';
        $($clone).insertBefore($tr);
        if ($(this).closest('.row').siblings('.row').length == 4) {
            $('.add-new-var').hide();
        }
        initTrashBtn();
        initSelect();
    });
    initSelect();


    if (!!$search.id) {
        $.get('/offer/detail?id=' + $search.id, function (res) {
            console.log(res);
            var offer = res.data;
            $('[name=name]').val(offer.name);
            offer.thumbnail && $('[name=thumbnail]').val(offer.thumbnail);
            if (!!offer.statusPt) {
                setChecked($('[name=statusPt][value=' + offer.statusPt + ']'));
            }
            getProduct(offer.productId, offer.code);

            $('[name=desc1]').val(offer.desc1);
            $('[name=tags]').val(offer.tags);
            offer.files && offer.files.map(function (item) {
                return initImg(item.url, offer.thumbnail == item.url, item.id);
            })
            initEditor('editor-profile', offer.detail);
            if (offer.multiVars == '1') {
                $('.single-var-shop-panel').hide();
                $('.multi-vars-shop-panel').show();
            }
            if (!!offer.varsNameIds) {
                var values = offer.varsValueIds.split('=');
                offer.varsNameIds.split('=').map(function (item, index) {
                    var item = item.replace(/\,/ig, '');
                    if (!!item && item != '==') {
                        if ($('[name=spec]').length == 1 && index == 0) {
                            initCaseData(item, $('[name=spec]'), item, values[index].substr(1, values[index].length - 2).split(','));
                        } else {
                            $('.add-new-var').click();
                            initCaseData(item, $('.var-item').last().find('[name=spec]'), item, values[index].substr(1, values[index].length - 2).split(','));
                        }
                    }
                })
                $('.vars').hide();
                $('.eidt-vars').show();
                $('.prices').show();
                $('#prices').html(ejs.render($('#price-template').html(), {list: offer.vars || []}));
                if (offer.vars.length && !!offer.vars[0].inventoryItemId) {
                    $('.eidt-vars').remove();
                }
                initBtn();
            }
            initSelectPicker({
                brand: offer.brand,
                categoryId: offer.categoryId,
                category: offer.categoryId,
                deliverPlace: offer.deliverPlace,
                // discountId: offer.discountId,
                sizeTable: offer.sizeTable,
                refundNotice: offer.refundNotice || '',//
                deliveryNotice: offer.deliveryNotice || '',
            });
        })
    } else {
        $('.multi-vars-shop-panel').show();
        $('.single-var-shop-panel').hide();
        initEditor('editor-profile');
        getProduct();
        initSelectPicker();
    }

    function getProduct(id, handler) {
        handler = handler || '';
        $.get(location.protocol + '//' + location.hostname + (location.port ? ":" + location.port : "") + '/shopify/products?handle=' + handler, function (products) {
            var $productId = $('[name=productId]');
            window.productsObj = products;
            products.map(function (item, index) {
                $productId.append('<option value="' + item.id + '"> [ ' + item.handle + ' ] ' + item.title + '</option>')
            });
            $productId.selectpicker({
                liveSearch: true,
            });
            if ($('.loading-products').length) {
                $('.loading-products').remove();
            }
            if (id || handler) {
                //if(window.productsObj)
                if (id) {
                    $productId.selectpicker('val', id);
                } else if (handler) {
                    var cur = _.find(window.productsObj, function (item) {
                        return item.handle == handler
                    });
                    if (cur) {
                        $productId.selectpicker('val', cur.id);
                    }
                }
            }
        })
    }

    /**
     * specId 规格Id
     * ctxt  元素上下文
     * 初始化规格级联数据
     */
    function initCaseData(specId, ctxt, specSelectedIdd, childSelected) {
        if (!!specSelectedIdd) {
            $(ctxt).closest('.col-sm-4').find('[name=spec]').selectpicker('val', specSelectedIdd);
        }
        if (window['spec-data-' + specId]) {
            selectpickerFn({
                ele: $(ctxt).closest('.row').find('[name=tags-item]'),
                list: window['spec-data-' + specId],
                multiple: true,
                name: 'tags-item',
            });
        } else {
            $.get('/category/list?type1=spec-data-' + specId + '&size=' + maxSize, function (res) {
                selectpickerFn({
                    multiple: true,
                    ele: $(ctxt).closest('.row').find('[name=tags-item]'),
                    list: res.list,
                    name: 'tags-item',
                    selected: childSelected || '',
                });
                window['spec-data-' + specId] = res.list;
            })
        }
    }

    /**
     * 规格数据初始化
     */
    function initSelect() {
        $('[name=spec]').map(function (index, ele) {
            selectEle({
                ele: $(ele),
                name: 'spec',
                placeholder: '请选择规格',
                url: '/category/list?type1=spec' + '&size=' + maxSize,
                change: function (data, ctxt) {
                    return initCaseData(data, ctxt);
                    if (window['spec-data-' + data]) {
                        selectpickerFn({
                            ele: $(ctxt).closest('.row').find('[name=tags-item]'),
                            list: window['spec-data-' + data],
                            multiple: true,
                            name: 'tags-item',
                        });
                    } else {
                        $.get('/category/list?type1=spec-data-' + data + '&size=' + maxSize, function (res) {
                            console.log(res);
                            selectpickerFn({
                                multiple: true,
                                ele: $(ctxt).closest('.row').find('[name=tags-item]'),
                                list: res.list,
                                name: 'tags-item',
                            });
                            window['spec-data-' + data] = res.list;
                        })
                    }
                }
            })
        })
    }

    onClick($('.single-var-shop'), function () {
        $('.single-var-shop-panel').show();
        $('.multi-vars-shop-panel').hide();
    })
    onClick($('.multi-vars-shop'), function () {
        $('.multi-vars-shop-panel').show();
        $('.single-var-shop-panel').hide();
    })
    initTrashBtn();
    function initTrashBtn() {
        onClick($('.trash-btn'), function () {
            if ($(this).closest('.row').siblings('.row').length <= 4) {
                $('.add-new-var').show();
            }
            if ($(this).closest('.row').siblings('.row').length == 2) { //
                return fnFail('请至少保留一个规格属性')
            } else { // 删除时，规格大于1时，可直接删除
                $(this).closest('.row').remove();
            }
        })
    }

    onClick($('.save-to-set-price'), function () { //
        var obj = {};
        window.values = [];
        $('.var-item').map(function (index, item) {
            var specs = $(item).find('[name=spec]').val();
            window.values = window.values.concat(window['spec-data-' + specs] || []);
            var specsItem = $(item).find('[name=tags-item]').val();
            obj[specs] = specsItem;
        });

        window.varItems = _.groupBy(window.values || [], 'id');
        var list = (doExchange(_.values(obj)));
        list = list.map(function (arr) { // 由id转换为标签
            return {
                vars: arr,
                name: arr.split(',').map(function (key) {
                    return window.varItems[key][0].name;
                }).join('·'),
                price: 0,
                actualPrice: 0,
                ptPrice: 0,
                thumbnail: ''
            };
        })
        $('.vars').hide();
        $('.eidt-vars').show();

        $('#prices').html(ejs.render($('#price-template').html(), {list: list}));
        $('#prices').show();
        initBtn();
    })

    var $upload = $('#ctlBtn');

    var $wrap = $('#uploader'),
        // 图片容器
        $queue = $wrap.find('.imgs'),
        // 状态栏，包括进度和控制按钮
        $statusBar = $wrap.find('.statusBar'),
        // 文件总体选择信息。
        $info = $statusBar.find('.info'),
        // 没选择文件之前的内容。
        $placeHolder = $wrap.find('.placeholder'),
        // 总体进度条
        $progress = $statusBar.find('.progress').hide(),
        // 添加的文件数量
        fileCount = 0,
        // 添加的文件总大小
        fileSize = 0,
        // 优化retina, 在retina下这个值是2
        ratio = window.devicePixelRatio || 1,
        // 缩略图大小
        thumbnailWidth = 110 * ratio,
        thumbnailHeight = 110 * ratio,

        // 可能有pedding, ready, uploading, confirm, done.
        state = 'ready',
        // 所有文件的进度信息，key为file id
        percentages = {},
        supportTransition = (function () {
            var s = document.createElement('p').style,
                r = 'transition' in s ||
                    'WebkitTransition' in s ||
                    'MozTransition' in s ||
                    'msTransition' in s ||
                    'OTransition' in s;
            s = null;
            return r;
        })(),
        // WebUploader实例
        uploader;
    // 初始状态图片上传前不会压缩
    uploader = new WebUploader.Uploader({
        dnd: '.imgs',
        disableGlobalDnd: true,
        chunked: true,
        paste: document.body,
        resize: true,
        // server: location.protocol + '//' + getDomainAndPort() + '/api/uploadOss',
        server: location.protocol + '//' + getDomainAndPort() + '/api/upload',
        pick: '#item-trigger',
        swf: '/admin/libs/webuplaoder-0.1.5/Uploader.swf',
    });//图片上传初始化
    var $list = $('.imgs');

    uploader.on('fileQueued', function (file) {
        var $li = ejs.render($('#img-item-template').html(), {
            url: '',
            forUpload: true,
            isThumbnail: false,
            id: file.id,
        })
        $li = $($li);
        var $img = $li.find('img');
        $li.data(file);// data
        $($li).insertBefore($('.item-trigger').closest('.col-sm-4'));
        onClick($li.find('.image-cover span'), function () {
            if ($(this).index() == 0) {
                uploader.removeFile(file);
            }
        })
        uploader.makeThumb(file, function (error, src) {
            if (error) {
                $img.replaceWith('<span>不能预览</span>');
                return;
            }
            $img.attr('src', src);
        }, 222, 222);
        percentages[file.id] = [file.size, 0];
        file.rotation = 0;
    });

    // 负责view的销毁
    function removeFile(file) {
        var $li = $('#' + file.id);

        delete percentages[file.id];
        updateTotalProgress();
        $li.remove();
    }

    function updateTotalProgress() {
        return updateStatus();
        var loaded = 0,
            total = 0,
            spans = $progress.children(),
            percent;

        $.each(percentages, function (k, v) {
            total += v[0];
            loaded += v[0] * v[1];
        });
        percent = total ? loaded / total : 0;
        spans.eq(0).text(Math.round(percent * 100) + '%');
        spans.eq(1).css('width', Math.round(percent * 100) + '%');
        updateStatus();
    }

    function updateStatus() {
        var text = '', stats;

        if (state === 'ready') {
            text = '选中' + fileCount + '张图片，共' +
                WebUploader.formatSize(fileSize) + '。';
        } else if (state === 'confirm') {
            stats = uploader.getStats();
            if (stats.uploadFailNum) {
                text = '已成功上传' + stats.successNum + '张照片至XX相册，' +
                    stats.uploadFailNum + '张照片上传失败，<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
            }
        } else {
            stats = uploader.getStats();
            text = '共' + fileCount + '张（' +
                WebUploader.formatSize(fileSize) +
                '），已上传' + stats.successNum + '张';
            if (stats.uploadFailNum) {
                text += '，失败' + stats.uploadFailNum + '张';
            }
        }
        $info.html(text);
    }

    function setState(val) {
        var file, stats;
        if (val === state) {
            return;
        }
        $upload.removeClass('state-' + state);
        $upload.addClass('state-' + val);
        state = val;
        switch (state) {
            case 'pedding':
                $placeHolder.removeClass('element-invisible');
                $queue.parent().removeClass('filled');
                $queue.hide();
                $statusBar.addClass('element-invisible');
                uploader.refresh();
                break;
            case 'ready':
                $placeHolder.addClass('element-invisible');
                $('#filePicker2').removeClass('element-invisible');
                $queue.parent().addClass('filled');
                $queue.show();
                $statusBar.removeClass('element-invisible');
                uploader.refresh();
                break;
            case 'uploading':
                $('#filePicker2').addClass('element-invisible');
                $progress.show();
                $upload.text('暂停上传');
                break;
            case 'paused':
                $progress.show();
                $upload.text('继续上传');
                break;
            case 'confirm':
                $progress.hide();
                $upload.text('开始上传').addClass('disabled');
                stats = uploader.getStats();
                if (stats.successNum && !stats.uploadFailNum) {
                    setState('finish');
                    return;
                }
                break;
            case 'finish':
                stats = uploader.getStats();
                if (stats.successNum) {
                    fnSuccess('上传成功');
                } else {
                    // 没有成功的图片，重设
                    state = 'done';
                    location.reload();
                }
                break;
        }
        updateStatus();
    }

    uploader.onUploadProgress = function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress span');
        $percent.css('width', percentage * 100 + '%');
        percentages[file.id][1] = percentage;
        updateTotalProgress();
    };

    uploader.onFileDequeued = function (file) {
        fileCount--;
        fileSize -= file.size;
        if (!fileCount) {
            setState('pedding');
        }
        removeFile(file);
        updateTotalProgress();
    };


    uploader.on('all', function (type) {
        var stats;
        switch (type) {
            case 'uploadFinished':
                setState('confirm');
                break;

            case 'startUpload':
                setState('uploading');
                break;

            case 'stopUpload':
                setState('paused');
                break;

        }
    });
    uploader.on('uploadSuccess', function (file, responese) {
        console.log(responese);
        console.log(file);
        $('#' + file.id)
            .find('.s-kit-image-item').removeClass('tmp').end()
            .find('img').attr('src', responese.data.path).end()
            .find('[name=fileIds]').val(responese.data.fileId).end()
            .find('.img-label').remove();

        $('#' + file.id).find('.image-cover').append('&nbsp;&nbsp;<span class="image-cover-crop">裁剪</span>');
        debugger;
        imgEvent();
        initClearFix()
    });
    uploader.onError = function (code) {
        alert('Eroor: ' + code);
    };
    uploader.uploadComplete = function (file) {
        console.log(file);
    };

    $upload.on('click', function () {
        //$('')
        if ($(this).hasClass('disabled')) {
            return false;
        }
        if (state === 'ready') {
            uploader.upload();
        } else if (state === 'paused') {
            uploader.upload();
        } else if (state === 'uploading') {
            uploader.stop();
        }
    });
    $upload.addClass('state-' + state);
    updateTotalProgress();

    /**
     * 上传商品图片
     */
    // onClick($('.item-trigger'), function () {
    //     var self = this;
    //     uploadFn('商品图片', {
    //         w: 400,
    //         h: 400,
    //         num: 12,
    //         labelNum: '12 upload-custom-label',
    //         noCrop: false,
    //         preview: 'left-top-preview'
    //     }, function (data) {
    //         closeLayer(data.layerIndex);
    //         //console.log(data);
    //         var thumbnail = $('[name=thumbnail].thumbnail').val();
    //         return initImg(data.path, !thumbnail, data.fileId);
    //
    //     })
    // })
    function initImg(url, isThumbnail, fileId) {
        var item = ejs.render($('#img-item-template').html(), {
            url: url,
            isThumbnail: isThumbnail,
            id: fileId,
        });
        if (!!isThumbnail) { // 默认设置为封面
            $('[name=thumbnail].thumbnail').val(url);//
        }
        $(item).insertBefore($('.item-trigger').closest('.col-sm-4'));
        imgEvent();
        initClearFix();

    }

    function imgEvent() {
        onClick($('.s-kit-image-item .image-cover span'), function () {
            if ($(this).hasClass('image-cover-crop')) { //裁剪
                var self = this;
                jcropFn('裁剪', {
                    w: 400,
                    h: 400,
                    num: 12,
                    labelNum: 12,
                    path: $(this).closest('.s-kit-image-item').find('img.item-image').attr('src'),
                    fileId: $(this).closest('.s-kit-image-item').find('[name=fileIds]').val(),
                    submit: function (path) {
                        //debugger;
                        $(self).closest('.s-kit-image-item').find('img.item-image').attr('src', path.path);
                        $(self).closest('.s-kit-image-item').find('.image-cover').append('<span class="image-cover-text">设为封面</span>');
                        $(self).closest('.s-kit-image-item').find('.image-cover-crop').remove();//移除裁剪功能
                        imgEvent();
                        initClearFix();
                    }
                })
            } else if ($(this).hasClass('image-cover-text')) { //设置为封面
                $('.img-label').remove();
                $('<div class="img-label">封面图片</div>').insertAfter($(this).closest('.image-cover'));
                $('[name=thumbnail].thumbnail').val($(this).closest('.image-cover').siblings('img').attr('src'))
            } else { // 移除
                $(this).closest('.col-sm-4').remove();
                initClearFix();
            }
        });
    }

    function initClearFix() {
        $('.imgs > .clearfix').remove();
        $('.imgs > .col-sm-4').map(function (index, item) {
            if ((index + 1) % 3 == 0) {
                $('<div class="clearfix"></div>').insertAfter($(item));
            }
        })
    };


    /**
     *
     */
    function initBtn() {
        /**
         * 同步库存
         */
        onClick($('.syn-sku'), function () {
            if (!$('[name=productId]').val()) {
                return fnFail('请选择商品并输入对应规格的SKU值');
            }
            var productId = $('[name=productId]').val();
            var skusObj = _.groupBy(_.groupBy(window.productsObj, 'id')[productId][0].variants, 'sku');
            $('[name=sku]').map(function (index, item) {
                if (!!$(item).val()) {
                    var $sku = $(item).closest('.row').find('[name=number]');
                    if (skusObj[$(item).val()] && skusObj[$(item).val()].length) {
                        $(item).closest('.row').find('[name=number]').val(skusObj[$(item).val()][0].inventory_quantity);
                        $(item).closest('.row').find('[name=number]').val(skusObj[$(item).val()][0].inventory_quantity);
                        $(item).closest('.row').find('[name=inventoryItemId]').val(skusObj[$(item).val()][0].inventory_item_id);
                        $sku.removeClass('border-red').addClass('border-success');
                    } else {
                        $sku.addClass('border-red').removeClass('border-success');
                        alert('SKU为' + $(item).val() + '的规格组合异常，系统无法比对Shopify数据同步库存');
                    }
                }
            });

        })
        /**
         * 上传商品规格图片
         */
        onClick($('#prices .fa-cloud-upload').closest('a'), function () {
            var self = this;
            uploadFn('规格缩略图', {
                w: 500,
                h: 500,
                num: 12,
                labelNum: '12 upload-custom-label',
                noCrop: false,
                preview: 'left-top-preview'
            }, function (data) {
                closeLayer(data.layerIndex);
                if ($(self).find('img')) {
                    $(self).append('<img src="' + data.path + '" style="height: 100%;" />')
                } else {
                    $(self).find('img').attr('src', data.path)
                }
                $(self).siblings('input').val(data.path);
            });
        })

        /**
         *  编辑规格按钮
         */
        onClick($('.eidt-vars'), function () {
            $('.vars').show();
            $('.eidt-vars').hide();
            $('#prices').hide();
            $('.cancel-eidt-vars').show();
        })
        onClick($('.cancel-eidt-vars'), function () {
            $('.vars').hide();
            $('.cancel-eidt-vars').hide();
            $('.eidt-vars').show();
            $('#prices').show();
        })
    }

    function initSelectPicker(opt) {
        opt = opt || {};
        $.when(
            parent.window.getDataByUrl(config.queryAccount, "deliverPlaces"),
            $.get('/category/list?type1=shop-category&level=2&size=' + maxSize),
            $.get('/category/list?type1=brand&size=' + maxSize),
            $.get('/category/list?type1=country&size=' + maxSize),
            // $.get('/category/list?type1=discount&size=' + maxSize),
            $.get('/tpl/list?type1=3&size=' + maxSize),// 尺码对照表
            $.get('/tpl/list?type1=2&size=' + maxSize),// 配送提醒
            $.get('/tpl/list?type1=1&size=' + maxSize)
            // 退货须知
        ).then(function (deliverPlace, category, brand, country,
                         // /discount,
                         sizeTable,
                         deliveryNotice,
                         refundNotice) {
            deliverPlace = deliverPlace;
            brand = brand[0].list;
            // discount = discount[0].list;
            country = country[0].list;
            category = category[0].list;
            sizeTable = sizeTable[0].list;
            refundNotice = refundNotice[0].list;
            deliveryNotice = deliveryNotice[0].list;//
            window.sizeTable = _.groupBy(sizeTable, 'id');
            window.deliveryNotice = _.groupBy(deliveryNotice, 'id');
            window.refundNotice = _.groupBy(refundNotice, 'id');
            window.brand = _.groupBy(brand, 'id');
            // window.discountId = _.groupBy(discount, 'id');
            window.deliverPlace = _.groupBy(country, 'id');
            window.categoryId = _.groupBy(category, 'id');


            var $deliverPlace = $('[name=deliverPlace]');
            if (!$deliverPlace.find('option').length) {
                country.map(function (item, index) {
                    $deliverPlace.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            }

            var $brand = $('[name=brand]');
            if (!$brand.find('option').length) {
                brand.map(function (item, index) {
                    $brand.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            }
            // var $discount = $('[name=country]');
            // if (!$discount.find('option').length) {
            //     discount.map(function (item, index) {
            //         $discount.append('<option value="' + item.id + '">' + item.name + '</option>')
            //     });
            // }
            var $sizeTable = $('[name=sizeTable]');
            if (!$sizeTable.find('option').length) {
                sizeTable.map(function (item, index) {
                    $sizeTable.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            }
            var $deliveryNotice = $('[name=deliveryNotice]');
            if (!$deliveryNotice.find('option').length) {
                deliveryNotice.map(function (item, index) {
                    $deliveryNotice.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            }
            var $refundNotice = $('[name=refundNotice]');
            if (!$refundNotice.find('option').length) {
                refundNotice.map(function (item, index) {
                    $refundNotice.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            }
            // var $discount = $('[name=discountId]');
            // if (!$discount.find('option').length) {
            //     discount.map(function (item, index) {
            //         $discount.append('<option value="' + item.id + '">' + item.name + '</option>')
            //     });
            // }


            var $categoryId = $('[name=categoryId]');
            if (!$categoryId.find('option').length) {
                category.map(function (item, index) {
                    $categoryId.append('<option value="' + item.id + '">' + item.name + '</option>')
                });
            }


            $('.slid-bars').find('[name="categoryId"]')
                .selectpicker({
                    liveSearch: true,
                })
                .change(function (e) {
                    //$('#registrationForm').data('formValidation').revalidateField('categoryId');
                }).end()
                .find('[name="refundNotice"]')
                .selectpicker({
                    liveSearch: true,
                })
                .change(function (e) {
                    // $('#registrationForm').data('formValidation').revalidateField('sizeTable');
                })
                .end()
                .find('[name="deliveryNotice"]')
                .selectpicker({
                    liveSearch: true,
                })
                .change(function (e) {
                    // $('#registrationForm').data('formValidation').revalidateField('sizeTable');
                })
                .end()
                .find('[name="sizeTable"]')
                .selectpicker({
                    liveSearch: true,
                })
                .change(function (e) {
                    // $('#registrationForm').data('formValidation').revalidateField('sizeTable');
                })
                .end()
                // .find('[name="discountId"]')
                // .selectpicker({
                //     liveSearch: true,
                // })
                // .change(function (e) {
                //     //$('#registrationForm').data('formValidation').revalidateField('discountId');
                // })
                // .end()
                .find('[name="deliverPlace"]')
                .selectpicker({
                    liveSearch: true,
                })
                .change(function (e) {
                    // $('#registrationForm').data('formValidation').revalidateField('deliverPlace');
                })
                .end()
                .find('[name="brand"]')
                .selectpicker({
                    liveSearch: true,
                })
                .change(function (e) {

                    //$('#registrationForm').data('formValidation').revalidateField('brand');
                })
                .end();
            if (opt.sizeTable) {
                $('[name="sizeTable"]').selectpicker('val', opt.sizeTable);
            }
            if (opt.deliveryNotice) {
                $('[name="deliveryNotice"]').selectpicker('val', opt.deliveryNotice);
            }
            if (opt.refundNotice) {
                $('[name="refundNotice"]').selectpicker('val', opt.refundNotice);
            }
            if (opt.brand) {
                $('[name="brand"]').selectpicker('val', opt.brand);
            }
            if (opt.deliverPlace) {
                $('[name="deliverPlace"]').selectpicker('val', opt.deliverPlace);
            }
            // if (opt.discountId) {
            //     $('[name="discountId"]').selectpicker('val', opt.discountId);
            // }
            if (opt.categoryId) {
                $('[name="categoryId"]').selectpicker('val', opt.categoryId);
            }
        })
    }

    function submit(status) {
        if ($('.image-cover-crop').length) {
            if (!confirm('您还有上传后未裁剪的图片，是否确认提交？')) {
                return;
            }
        }
        var form = {status: status || '0'};
        form.name = $('[name=name]').val();
        if (!form.name) {
            return fnFail('请填写商品名称');
        }
        form.desc1 = $('[name=desc1]').val();
        if (!form.desc1) {
            return fnFail('请填写商品简述(副标题)');
        }
        form.detail = window.editor.getContent();
        if (!form.detail) {
            return fnFail('请填写商品详情');
        }
        if (!$('[name=fileIds]').length) {
            return fnFail('请上传商品图片！')
        }
        var fileIds = [], needUpload = 0;
        $('[name=fileIds]').map(function (index, item) {
            if ($(item).closest('.tmp').length) {
                needUpload++;
            } else {
                fileIds.push($(item).val());
            }
        });
        if (needUpload > 0) {
            return alert('您有' + needUpload + '个待上传的图片，请上传完毕后再次提交')
        }
        ///
        form.fileIds = fileIds.join(',');
        if ($('.single-var-shop-panel').is(':visible')) { // 单规格商品
            form.price = $('[name=price]').val();
            form.priceMin = $('[name=price]').val();
            form.actualPrice = $('[name=actualPrice]').val();
            form.actualPriceMin = $('[name=actualPrice]').val();
            form.ptPrice = $('[name=ptPrice]').val();
            form.ptPriceMin = $('[name=ptPrice]').val();
            form.multiVars = 0;
        } else { // 多规格商品
            var vars = {vars: []};
            var prices = [], actualPrices = [], ptPrices = [], numbers = 0;
            $('#prices').find('.row').map(function (index, item) {
                if (!!$(item).find('[name=price]').length) {
                    var item1 = {};
                    item1.vars = _.sortBy(($(item).find('.col-sm-4').data('id') + '').split(',').map(function (item) {
                        return parseInt(item)
                    })).join(','); // 固定顺序
                    item1.name = $(item).find('.col-sm-4').html();
                    $(item).find('input').map(function (index2, item2) {
                        item1[$(item2).attr('name')] = $(item2).val();
                        if ($(item2).attr('name') == 'price') prices.push(parseFloat($(item2).val()));
                        if ($(item2).attr('name') == 'actualPrice') actualPrices.push(parseFloat($(item2).val()));
                        if ($(item2).attr('name') == 'ptPrice') ptPrices.push(parseFloat($(item2).val()));
                        if ($(item2).attr('name') == 'number') numbers = floatTool.add(parseFloat($(item2).val()), numbers);
                    });
                    vars.vars.push(item1);
                }
            });
            form.price = _.max(prices);
            form.priceMin = _.min(prices);
            form.actualPrice = _.max(actualPrices);
            form.actualPriceMin = _.min(actualPrices);
            form.ptPrice = _.max(ptPrices);
            form.ptPriceMin = _.min(ptPrices);
            form.multiVars = 1;
            form.saleNum = numbers || 0;// 总库存
            getQueryStr(vars).map(function (item) {
                var key_v = item.split('=');
                form[key_v[0]] = key_v[1];
            });
            var varsNameIds = [], varsValueIds = [];
            $('.vars .var-item').map(function (index, item) {
                varsNameIds.push($(item).find('[name=spec]').val());
                varsValueIds.push($(item).find('[name=tags-item]').val());
            });
            form.varsNameIds = varsNameIds.map(function (item) {

                return ',' + item + ',';
            }).join('=')
            form.varsValueIds = varsValueIds.map(function (item) {
                return ',' + item + ',';
            }).join('=')
        }
        if ($('[name=brand]').val()) {
            form.brand = $('[name=brand]').val();
        } else {
            return fnFail('请选择品牌')
        }
        if ($('[name=categoryId]').val()) {
            form.categoryId = $('[name=categoryId]').val();
        } else {
            return fnFail('请选择分类')
        }
        if ($('[name=refundNotice]').val()) {
            form.refundNotice = $('[name=refundNotice]').val();
        } else {
            return fnFail('请选择退款须知');
        }
        if ($('[name=deliveryNotice]').val()) {
            form.deliveryNotice = $('[name=deliveryNotice]').val();
        } else {
            return fnFail('请选择配送说明');
        }

        // if ($('[name=discountId]').val()) {// 折扣
        //     form.discountId = $('[name=discountId]').val();
        // }
        //form.status = $('[name=status]:checked').val();
        form.deliverPlace = $('[name=deliverPlace]').val();
        form.thumbnail = $('[name=thumbnail].thumbnail').val();
        form.sizeTable = $('[name=sizeTable]').val();
        form.statusPt = $('[name=statusPt]:checked').val();
        form.productId = $('[name=productId]').val();
        if (!!$search.id) {
            form.id = $search.id;
        }
        $.post(!!$search.id ? "/offer/update" : "/offer/create", form, function (res) {
            if (res.code == 200) {
                if ('1' == status && form.id) {
                    fnSuccess('保存成功,系统将检测当前商品是否满足上架条件！');
                    return $.post("/offer/groundingCheck/" + form.id, {}, function (res) {
                        if (res.code == 200) {
                            if (res.list == 0) {
                                fnSuccess('商品已满足上架条件，并自动上架');
                            } else {
                                fnFail('商品不能上架，因未满足如下条件：\n' + _.map(res.list, function (ite, index) {
                                        return (index + 1) + ',' + ite;
                                    }).join('\n'));
                            }
                        }
                    })
                } else {
                    return alert('保存成功');
                }
            } else {
                return fnFail(res.error || '保存失败');
            }
        })
    }

    onClick($('.btn-up'), function () {
        submit(1)
    })

    /**
     * 保存商品
     */
    onClick($('.btn-save'), function () {
        submit(0);////
    })

    function upload(lab, ratio) {
        ratio = ratio || {};
        dialogForm({
            title: '上传' + lab,
            fullScreen: true,
            data: [

                {
                    type: 'upload-dialog',
                    label: lab,
                    require: true, // 是否必填
                    name: 'upload',
                    labelStyle: ratio.style || '',
                    value: '',

                    num: 8,
                    labelNum: 2,
                    validate: 'ipt  validate[required]',
                    btnClass: 'select-file',
                    btn: {
                        class_: '9 col-xs-offset-1'
                    }
                },
            ],
            shown: function (obj) {
                $('.select-file').$upload({
                    w: ratio.w || 185,
                    h: ratio.h || 164,

                    submit: function (path) {
                        closeLayer(obj.index);
                        $('.preview').attr('src', path);
                    }
                })
            },
            noForm: true,
            submit: function (data) {
            }
        });
    }

    var self = this;

    function genForm() {
        dialogForm({
            eleId: 'form',
            title: '',
            data: arg.data,
            shown: arg.shown || function () {
            },
            submit: function (data) {
                data.img = $('.preview').attr('src');
                var url = arg.add;
                if ($search.id) {
                    data.id = $search.id;
                    url = arg.update;
                }
                if (data.editorValue) {
                    data.profile = data.editorValue
                }
                if (arg.reform) {
                    data = arg.reform(data);
                }
                $.post(url, data, function (res) {
                    if (res.code == 200) {
                        fnSuccess('操作成功！');
                        window.location.href = './index.html?type=' + $search.type
                    } else {
                        fnFail(res.error || '操作失败！')
                    }
                });
            }
        }, true);
    }


    /**
     * 富文本编辑器
     * @param id
     */
    function initEditor(id, content, opt) {
        opt = opt || {};
        window.editor = UE.getEditor(id, {
            //工具栏
            toolbars: [[
                'Source',
                'fullscreen', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'strikethrough', , 'removeformat', 'formatmatch',
                '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'link', 'unlink', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'indent', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
                'insertframe', '|',
                'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload',
                'horizontal', 'insertvideo'
                // ,'preview'
            ]],
            lang: "zh-cn",//字体
            fontfamily: [
                {label: '', name: 'songti', val: '宋体,SimSun'},
                {label: '', name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
                {label: '', name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
                {label: '', name: 'heiti', val: '黑体, SimHei'},
                {label: '', name: 'lishu', val: '隶书, SimLi'},
                {label: '', name: 'andaleMono', val: 'andale mono'},
                {label: '', name: 'arial', val: 'arial, helvetica,sans-serif'},
                {label: '', name: 'arialBlack', val: 'arial black,avant garde'},
                {label: '', name: 'comicSansMs', val: 'comic sans ms'},
                {label: '', name: 'impact', val: 'impact,chicago'},
                {label: '', name: 'timesNewRoman', val: 'times new roman'}
            ],//字号
            'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36],
            enableAutoSave: true,
            autoHeightEnabled: true,
            initialFrameHeight: '400px',
            initialFrameWidth: '100%',
            readonly: false,
            initialFrameHeight: 'auto',
            whitList: {
                a: ['target', 'href', 'title', 'class', 'style'],
                abbr: ['title', 'class', 'style'],
                address: ['class', 'style'],
                area: ['shape', 'coords', 'href', 'alt'],
                article: [],
                aside: [],
                audio: ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'],
                b: ['class', 'style'],
                bdi: ['dir'],
                bdo: ['dir'],
                big: [],
                blockquote: ['cite', 'class', 'style'],
                br: [],
                caption: ['class', 'style'],
                center: [],
                cite: [],
                code: ['class', 'style'],
                col: ['align', 'valign', 'span', 'width', 'class', 'style'],
                colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'],
                dd: ['class', 'style'],
                del: ['datetime'],
                details: ['open'],
                div: ['class', 'style'],
                dl: ['class', 'style'],
                dt: ['class', 'style'],
                em: ['class', 'style'],
                font: ['color', 'size', 'face'],
                footer: [],
                h1: ['class', 'style'],
                h2: ['class', 'style'],
                h3: ['class', 'style'],
                h4: ['class', 'style'],
                h5: ['class', 'style'],
                h6: ['class', 'style'],
                header: [],
                hr: [],
                i: ['class', 'style'],
                img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', '_url', 'loadingclass', 'class', 'data-latex'],
                ins: ['datetime'],
                li: ['class', 'style'],
                mark: [],
                nav: [],
                ol: ['class', 'style'],
                p: ['class', 'style'],
                pre: ['class', 'style'],
                s: [],
                section: [],
                small: [],
                span: ['class', 'style'],
                sub: ['class', 'style'],
                sup: ['class', 'style'],
                strong: ['class', 'style'],
                table: ['width', 'border', 'align', 'valign', 'class', 'style'],
                tbody: ['align', 'valign', 'class', 'style'],
                td: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                tfoot: ['align', 'valign', 'class', 'style'],
                th: ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                thead: ['align', 'valign', 'class', 'style'],
                tr: ['rowspan', 'align', 'valign', 'class', 'style'],
                tt: [],
                u: [],
                ul: ['class', 'style'],
                video: ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style'],
                source: ['src', 'type'],
                // embed:['type','class','pluginspage','src','wdith','height','align','style','wmode','play','autoplay',
                //     'loop','menu','allowsscriptaccess','allowfullscreen','controls','preload'
                // ],
                iframe: ['src', 'class', 'height', 'width', 'max-width', 'max-height', 'align',
                    'frameborder', 'allowfullscreen'
                ]
            }
        });
        window.editor.ready(function (ueditor) {

            if (opt && opt.source) { // 源码模式
                setTimeout(function () {
                    if (window.editor.queryCommandState('source') != 1) {//判断编辑模式状态:0表示【源代码】HTML视图；1是【设计】视图,即可见即所得；-1表示不可用
                        window.editor.execCommand('source'); //切换到【设计】视图
                    }
                }, 500);
            }
            if (content) {
                window.editor.setContent(content);
            }

        });

        window.editor.addListener('contentChange', function (editor_) {
            var self = this;
            content_ = self.getContent();
        });
    }

});